package com.example.board.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.example.board.mapper.PinCrownMapper;
import com.example.board.pojo.dto.DeptDto;
import com.example.board.pojo.dto.UserDto;
import com.example.board.pojo.vo.DistributorVo;
import com.example.board.pojo.vo.TopSaleStaticVo;
import com.example.board.service.PinCrownService;
import com.example.board.util.DateQuery;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.formula.functions.T;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class PinCrownServiceImpl implements PinCrownService {


    private final PinCrownMapper pinCrownMapper;

    @Override
    public List<TopSaleStaticVo> getTopSaleStatic() {

        //查询所有业务员姓名地址
        List<UserDto> salesDetail = pinCrownMapper.findAllSales();


        //返单率 当月返单的次数/当月总下单次数  返单：这月下单人，在上月下单
        //并且状态在 2,3,12 中
        //当月 开始和结束
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startMoth = LocalDateTime.parse(DateQuery.getMothStart(), df);
        LocalDateTime enMoth = LocalDateTime.parse(DateQuery.getMothEnd(), df);

        //查询当月下单销售总单
        List<Long> userIds = salesDetail.stream().map(UserDto::getId).collect(Collectors.toList());
        List<UserDto> orderNumber = pinCrownMapper.findOrderNumberNowMothAndUID(userIds, startMoth, enMoth);

        //新增客户数 这周录入
        LocalDateTime startWeek = LocalDateTime.parse(DateQuery.getWeekStart(), df);
        List<UserDto> userRecordNumber = pinCrownMapper.findUserRecordNumberWeek(userIds,startWeek);

        //客户总数，一开始到现在
        List<UserDto> userRecordNumbers = pinCrownMapper.findUserRecordNumber(userIds);

        // 成交金额 这周
        List<UserDto> userOrderAmountWeek = pinCrownMapper.findUserOrderAmountWeek(userIds,startWeek);

        Map<Long, Long> collect = new HashMap<>();
        //获取当月下单客户和销售的id
        List<UserDto> orderNumberAndUID = pinCrownMapper.findOrderNumberAndUID(startMoth, enMoth);
        if (!CollectionUtils.isEmpty(orderNumberAndUID)) {
            List<Long> userRecordIds = orderNumberAndUID.stream().map(UserDto::getUserRecordId).collect(Collectors.toList());
            //查询上月是否有单 状态在 2,3,12
            LocalDateTime startMothLast = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
            LocalDateTime endMothLast = LocalDateTime.parse(DateQuery.getMothEndLast(), df);
            List<UserDto> orderRateNumber = pinCrownMapper.findOrderRateNumber(userRecordIds, startMothLast, endMothLast);
            //使用Id分组 key为Id,value为返单次数
            // TODO:无论返单多少次算一单 后续可能按下单数来 ，改为先查上月下单用户，在查本月下单用户，用sum
//            collect = orderRateNumber.stream().filter(x -> x.getTotalOrder() > 0).collect(Collectors.groupingBy(UserDto::getId, Collectors.summingInt(UserDto::getTotalOrder)));
            collect = orderRateNumber.stream().filter(x -> x.getTotalOrder() > 0).collect(Collectors.groupingBy(UserDto::getId, Collectors.counting()));

        }

        //开始凑数据

        List<TopSaleStaticVo> topSaleStaticVos = new ArrayList<>();
        for (UserDto userDto : salesDetail) {
            TopSaleStaticVo topSaleStaticVo = new TopSaleStaticVo();
            topSaleStaticVo.setId(userDto.getId());
            topSaleStaticVo.setAvatarUrl(userDto.getAvatar());
//                topSaleStaticVo.setTop();
            topSaleStaticVo.setCustomerNew(0);
            topSaleStaticVo.setSalesman(userDto.getUserName());
            topSaleStaticVo.setTeamName(userDto.getProvince() + "-" + userDto.getCity() + "-" + userDto.getDistrict());
            topSaleStaticVo.setCustomerTotal(0);
            topSaleStaticVo.setTransactionAmount(0.00);
            topSaleStaticVo.setOrderAmount(0.00);
            topSaleStaticVo.setRateReturn(new BigDecimal(0));

            //新增客户数 这周录入
            if (!CollectionUtils.isEmpty(userRecordNumber)) {
                for (UserDto dto : userRecordNumber) {
                    if (dto.getId().equals(userDto.getId())) {
                        topSaleStaticVo.setCustomerNew(dto.getCustomerWeek());
                        break;
                    }
                }
            }

            //客户总数
            if (!CollectionUtils.isEmpty(userRecordNumbers)) {
                for (UserDto recordNumber : userRecordNumbers) {
                    if (recordNumber.getId().equals(userDto.getId())) {
                        topSaleStaticVo.setCustomerTotal(recordNumber.getCustomer());
                        break;
                    }
                }
            }

            //成交金额
            if (!CollectionUtils.isEmpty(userOrderAmountWeek)) {
                for (UserDto dto : userOrderAmountWeek) {
                    if (dto.getId().equals(userDto.getId())) {
                        topSaleStaticVo.setTransactionAmount(dto.getOrderAmountWeek());
                        break;
                    }
                }
            }

            //返单率
            //返单数
            Long aDouble = 0L;
            if (!CollectionUtils.isEmpty(collect) && collect.get(userDto.getId()) != null) {
                aDouble = collect.get(userDto.getId());
            }
//            System.out.println("DistributorServiceImpl "+collect.get(userDto.getId())+" : "+ userDto.getId());

            if (!CollectionUtils.isEmpty(orderNumber)) {
                for (UserDto dto : orderNumber) {
                    //总下单的数量   //返单数量不为空
                    if (dto.getId().equals(userDto.getId()) && dto.getTotalOrder()!= null && dto.getTotalOrder() !=0 ) {
//                        System.out.println("DistributorServiceImpl "+collect.get(userDto.getId())+" : "+ userDto.getId()+" : "+dto.getTotalOrder());
                        topSaleStaticVo.setRateReturn(new BigDecimal(aDouble).divide(BigDecimal.valueOf(dto.getTotalOrder()), 2, RoundingMode.HALF_UP));
                        break;
                    }
                }

            }

            topSaleStaticVos.add(topSaleStaticVo);
        }
        List<TopSaleStaticVo> collect1 = topSaleStaticVos.stream().sorted(Comparator
                .comparingDouble(TopSaleStaticVo::getTransactionAmount).reversed()
                .thenComparing(TopSaleStaticVo::getCustomerTotal, Comparator.reverseOrder())).collect(Collectors.toList());
        int i = 1;
        for (TopSaleStaticVo topSaleStaticVo : collect1) {
            topSaleStaticVo.setTop(i);
            i++;
        }


        return collect1;
    }

    @Override
    public List<DistributorVo> getTopDistributorStatic() {

        //当月 开始和结束
        DateTimeFormatter df = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        LocalDateTime startMoth = LocalDateTime.parse(DateQuery.getMothStart(), df);
        LocalDateTime enMoth = LocalDateTime.parse(DateQuery.getMothEnd(), df);

        //查询部门名称 id
        List<DeptDto> deptDetail = pinCrownMapper.findDeptNAId();
        List<Long> deptIds = deptDetail.stream().map(DeptDto::getId).collect(Collectors.toList());
        //部门下销售客户总数
        List<DeptDto> deptNumbers = pinCrownMapper.findDeptNumbers(deptIds);

        //部门下销售本周新增客户
        LocalDateTime startWeek = LocalDateTime.parse(DateQuery.getWeekStart(), df);
        List<DeptDto> deptNumberWeek = pinCrownMapper.findDeptNumberWeek(deptIds,startWeek);

        //部门下销售本周成交金额
        List<DeptDto> deptOrderAmountWeek = pinCrownMapper.findOrderAmountWeek(deptIds,startWeek);

        //查询本月部门下单用户id
        List<DeptDto> DeptOrderUserRecords = pinCrownMapper.findDeptOrderUserRecord(deptIds,startMoth,enMoth);

        //本周总下单数量
        List<DeptDto> DeptOrderNumbers = pinCrownMapper.findOrderNumbers(deptIds,startMoth,enMoth);

        List<DistributorVo> distributorVos =new ArrayList<>();

        Map<Long, Integer> collect = new HashMap<>();
        if (!CollectionUtils.isEmpty(DeptOrderUserRecords)) {
            List<Long> userRecordIds = DeptOrderUserRecords.stream().map(DeptDto::getUserRecordId).collect(Collectors.toList());
            //查询上月是否有单 状态在 2,3,12
            LocalDateTime startMothLast = LocalDateTime.parse(DateQuery.getMothStartLast(), df);
            LocalDateTime endMothLast = LocalDateTime.parse(DateQuery.getMothEndLast(), df);
            List<DeptDto> orderRateNumber = pinCrownMapper.findDeptOrderRateNumber(userRecordIds, startMothLast, endMothLast);
            //使用Id分组 key为Id,value为返单次数
            collect = orderRateNumber.stream().filter(x -> x.getTotalOrder() > 0).collect(Collectors.groupingBy(DeptDto::getId, Collectors.summingInt(DeptDto::getTotalOrder)));

        }

        //凑数据
        for (DeptDto deptDto : deptDetail) {
            DistributorVo distributorVo = new DistributorVo();
            distributorVo.setId(deptDto.getId());
//            distributorVo.setTop();
            distributorVo.setSalesman(deptDto.getName());
//            distributorVo.setAvatarUrl();
            distributorVo.setRateReturn(new BigDecimal(0));
            distributorVo.setTeamName(deptDto.getName());
            distributorVo.setCustomerNew(0);
            distributorVo.setCustomerTotal(0);
            distributorVo.setTransactionAmount(0.00);

            //部门下销售客户总数
            if (!CollectionUtils.isEmpty(deptNumbers)){
                for (DeptDto deptNumber : deptNumbers) {
                    if (deptNumber.getId().equals(deptDto.getId())){
                        distributorVo.setCustomerTotal(deptNumber.getCustomer());
                        break;
                    }
                }
            }

            //本周客户
            if (!CollectionUtils.isEmpty(deptNumberWeek)){
                for (DeptDto dto : deptNumberWeek) {
                    if (dto.getId().equals(deptDto.getId())){
                        distributorVo.setCustomerNew(dto.getCustomerWeek());
                        break;
                    }
                }
            }
            //成交金额本周
            if (!CollectionUtils.isEmpty(deptOrderAmountWeek)){
                for (DeptDto dto : deptOrderAmountWeek) {
                    if (dto.getId().equals(deptDto.getId())){
                        distributorVo.setTransactionAmount(dto.getOrderAmountWeek());
                        break;
                    }
                }
            }
            //返单
            int aDouble = 0;
            if (!CollectionUtils.isEmpty(collect) && collect.get(deptDto.getId()) != null) {
                aDouble = collect.get(deptDto.getId());
            }
            System.out.println("返单 "+aDouble+" : "+" : "+deptDto.getId());

            if (!CollectionUtils.isEmpty(DeptOrderNumbers)) {
                for (DeptDto dto : DeptOrderNumbers) {
                    //总下单的数量   //返单数量不为空
                    if (dto.getId().equals(deptDto.getId()) && dto.getTotalOrder() != null && dto.getTotalOrder() !=0 ) {
                        System.out.println("返单 "+aDouble+" : "+dto.getTotalOrder()+" : "+deptDto.getId());
                        distributorVo.setRateReturn(new BigDecimal(aDouble).divide(BigDecimal.valueOf(dto.getTotalOrder()), 2, RoundingMode.HALF_UP));
                        break;
                    }
                }

            }
            distributorVos.add(distributorVo);
        }
        List<DistributorVo> collect1 = distributorVos.stream().sorted(Comparator.comparingDouble(DistributorVo::getTransactionAmount)
                .reversed().thenComparing(DistributorVo::getCustomerTotal, Comparator.reverseOrder())).collect(Collectors.toList());
        int i =1;
        for (DistributorVo distributorVo : collect1) {
            distributorVo.setTop(i);
            i++;
        }
        return collect1 ;
    }
}
